package cn.com.cnxfs.relaxchat;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

public class NewsFragment extends Fragment {
    private Context context;
    private int uid; //当前登录用户id
    private Adapter_News adapter;
    private static List<News> news = new ArrayList<>();
    private MyDatabaseHelper databaseHelper;
    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;
    private LocalReceiver2 localReceiver2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = getActivity();
        databaseHelper = new MyDatabaseHelper(context, "database.db", null, 1); //打开本地数据库
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news, container, false);
    }

    void fresh(Adapter_News adapter){
        //从chat数据表里获取之前的聊天记录
        news.clear();
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT a.friend,ctime,var,f.state,nickname FROM chat as a,friend as f WHERE NOT EXISTS(" +
                "SELECT friend,ctime FROM chat as b WHERE b.ctime>a.ctime and a.friend=b.friend" +
                ") and f.friend=a.friend ORDER BY ctime DESC",null);
        if(cursor.moveToFirst()){  //查询时去掉重复值，找出有聊天记录的好友id
            do{
                //Log.d("查询结果好友id",cursor.getString(cursor.getColumnIndex("friend")));
                //Log.d("查询结果ctime",cursor.getString(cursor.getColumnIndex("ctime")));
                Log.d("查询结果var",cursor.getString(cursor.getColumnIndex("var")));
                Log.d("查询结果nickname",cursor.getString(cursor.getColumnIndex("nickname")));
                Log.d("查询结果state",cursor.getString(cursor.getColumnIndex("state")));
                News item = new News();
                item.setFriend(cursor.getInt(cursor.getColumnIndex("friend")));
                item.setNickname(cursor.getString(cursor.getColumnIndex("nickname")));
                item.setCtime(cursor.getString(cursor.getColumnIndex("ctime")));
                item.setNews(cursor.getString(cursor.getColumnIndex("var")));
                item.setState((byte)cursor.getInt(cursor.getColumnIndex("state"))); //消息是否已读
                news.add(item);
            }while(cursor.moveToNext());
        }
        cursor.close();
        adapter.notifyDataSetChanged(); //刷新UI
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        SharedPreferences preferences = Objects.requireNonNull(getActivity()).getSharedPreferences("db_login",MODE_PRIVATE);
        uid = Integer.parseInt(Objects.requireNonNull(preferences.getString("id", "0")));

        adapter = new Adapter_News(context, R.layout.layout_news, news);
        ListView listView = getActivity().findViewById(R.id.list_news);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(context, ChatActivity.class);
                //intent.putExtra("id",news.get(position).get);  //chat页面没用上
                intent.putExtra("uid",uid); //当前登录用户的id
                intent.putExtra("friend",news.get(position).getFriend());
                //intent.putExtra("username",news.get(position).get);  //实际上chat页面用不到username
                intent.putExtra("nickname",news.get(position).getNickname());
                intent.putExtra("state",(byte)0);
                startActivity(intent); //跳转到聊天页面
            }
        });
        fresh(adapter); //刷新消息列表

        //监听广播，收到新消息进入的广播时马上显示新消息到界面上
        localReceiver = new LocalReceiver();
        localBroadcastManager = LocalBroadcastManager.getInstance(context); //获取实例
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("cn.com.cnxfs.relaxchat.NEW_CHAT");
        localBroadcastManager.registerReceiver(localReceiver, intentFilter); //注册本地广播接收器
        localReceiver2 = new LocalReceiver2();
        intentFilter = new IntentFilter();
        intentFilter.addAction("cn.com.cnxfs.relaxchat.UPDATE_NEW_CHAT");
        localBroadcastManager.registerReceiver(localReceiver2 ,intentFilter);
    }

    @Override
    public void onDestroy() {  //别忘了取消注册广播接收器
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
        localBroadcastManager.unregisterReceiver(localReceiver2);
    }

    class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("news页面","收到本地广播！有新消息进入！");
            final int friend = intent.getIntExtra("friend",0);
            final News news_item = new News();
            news_item.setState((byte) 0); //未读消息
            news_item.setFriend(friend);
            news_item.setNews(intent.getStringExtra("var"));
            news_item.setCtime(intent.getStringExtra("ctime"));
            //从好友列表里查询friend对应的nickname
            final SQLiteDatabase db = databaseHelper.getWritableDatabase();
            Cursor cursor = db.query("friend",null,"friend="+friend,
                    null,null,null,"nickname");
            if(cursor.moveToFirst()){
                news_item.setNickname(cursor.getString(cursor.getColumnIndex("nickname")));
            }else { //如果对方不在好友列表里
                news_item.setNickname("【"+intent.getStringExtra("senderNickname")+"】");
            }
            cursor.close();
            boolean flag = false;
            for(News item : news){ //将新消息合并到List里
                if(item.getFriend()==friend){
                    news.remove(item); //如果已经存在，就更新这一项
                    news.add(news_item);
                    flag = true;
                    break;
                }
            }
            if(!flag)
                news.add(news_item);
            adapter.notifyDataSetChanged(); //更新UI
        }
    }

    class LocalReceiver2 extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("news页面", "收到本地广播2！刷新消息列表！");
            fresh(adapter);
        }
    }
}

class Adapter_News extends ArrayAdapter<News> {
    private int layoutId;

    Adapter_News(Context context, int layoutId, List<News> list){
        super(context, layoutId, list);
        this.layoutId = layoutId;
    }
    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final News item = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(layoutId, parent, false);
        TextView nickname = view.findViewById(R.id.news_friend);
        TextView new_ctime = view.findViewById(R.id.news_ctime);
        TextView news_str = view.findViewById(R.id.news_news);

        assert item != null;
        nickname.setText(item.getNickname());
        new_ctime.setText(item.getCtime());
        news_str.setText(item.getNews());
        if(item.getState()==0)
            news_str.setTextColor(Color.RED);
        else
            news_str.setTextColor(Color.BLACK);

        return view;
    }
}
